//function开启新的局部作用域 避免变量和函数命名冲突
(function () {
    let position = 'absolute';
    let snakes = [];
    function Snake(parent, options) {
        options = options || {};
        this.parent = parent;
        this.x = options.x || 0;
        this.y = options.y || 0;
        this.color = options.color || 'red';
        this.width = options.width || 40;
        this.height = options.height ||40;
        this.direction = options.direction || 'right';
        this.body = [
            {x:1,y:2,color:'blue'},
            {x:2,y:2,color:'blue'},
            {x:3,y:2,color:'red'},
        ];
    }
    Snake.prototype.render = function (map) {

        remove(map);
        for (let i = 0,len = this.body.length; i <len ; i++) {
            let snake = this.body[i];
            let div = document.createElement('div');
            map.appendChild(div);
            snakes.push(div);
            div.style.position = position;
            div.style.width = this.width+'px';
            div.style.height = this.height+'px';
            div.style.left = snake.x*this.width+'px';
            div.style.top = snake.y*this.height+'px';
            div.style.backgroundColor = snake.color;
        }
    };

    //控制snake的移动
    Snake.prototype.move = function(food,map) {

        for (let i=0,len = this.body.length; i <len-1; i++) {
            this.body[i].x = this.body[i+1].x;
            this.body[i].y = this.body[i+1].y;
        }
        let head = this.body[this.body.length-1];
        switch (this.direction) {
            case 'top':
                head.y-=1;
                break;
            case 'bottom':
                head.y+=1;
                break;
            case 'left':
                head.x-=1;
                break;
            case 'right':
                head.x+=1;
                break;
        }
        if (head.x === food.x && head.y === food.y) {
            this.body.push({
                x:food.x,
                y:food.y,
                color: food.color
            })
            food.render(map)
        }
    };

    function remove(map) {
        for (let i = snakes.length-1; i >=0 ; i--) {
            map.removeChild(snakes[i]);
            snakes.splice(snakes.length-1,1)
        }
    }
    //暴露构造函数给外部
    window.Snake = Snake;
})();
